/**
 * Copyright 2009-2015. qiuxj. All rights reserved. <a>http://www.firebird.com</a>
 */
package com.firebird.commons.url.Impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.firebird.commons.url.UrlRewrite;
import com.firebird.commons.util.StringUtil;

/**
 * @author qiuxj create on 2009-3-22
 *
 */
public class UrlRewriteImpl implements UrlRewrite {
	
	private Log log = LogFactory.getLog(this.getClass()); 
	
	/**
	 * get thisUrl transport's content
	 */
	public String spiderUrl(String url){
		if(StringUtil.isEmpty(url)){
			return "";
		}
		StringBuffer content = new StringBuffer("");
		try {
			URL reffer = new URL(url);
			HttpURLConnection http = (HttpURLConnection)reffer.openConnection();
			http.connect();
			if(http.getResponseCode() == HttpURLConnection.HTTP_OK){
				log.info("建立连接成功");
				InputStreamReader isr = new InputStreamReader(http.getInputStream(),"GB2312");
				BufferedReader reader = new BufferedReader(isr);
				while (reader.readLine() != null) {
					content.append(reader.readLine());
				}
				isr.close();
				reader.close();
			}
		} catch (MalformedURLException e) {
			log.info("URL错误");
			e.printStackTrace();
		} catch (IOException e) {
			log.info("读取文件流错误");
			e.printStackTrace();
		}
		return content.toString();
	}
	
	/**
	 * 暂时未实现写文件操作
	 * @param url
	 * @param filePath
	 * @param fileName
	 */
	public void spiderUrlToFile(String url,String filePath,String fileName) {
		String str = spiderUrl(url);
		File file = new File(fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(str.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			log.info("没发现要写入的文件");
			e.printStackTrace();
		} catch (IOException e) {
			log.info("写入文件流错误");
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}

}
